# from icecream import ic
import json
import os
import sys
import pandas as pd
import requests

from get_sql_res import gen_run_detail, gen_data_cluster
from get_response import gen_wafermap_config_mapping,gen_wafermap_config
from gen_info_dic import gen_info_dic

directory_path = os.path.dirname(os.path.abspath(__file__))
file_path=os.path.join(directory_path,'cfgs/mapping_char.json')
with open(file_path, 'r',encoding='utf8') as file:
    mapping_char = json.load(file)

def gen_RsDieSummary_one(info_dic, df_run_detail, wafer_id, sql_info):
    # 只选取有命中的rule
    result_ids = list(df_run_detail[(df_run_detail['triggered_count']!=0) & (
        df_run_detail['wafer_id'] == wafer_id)]['id'])
    if len(result_ids)==0:
        return pd.DataFrame(columns=['Lot ID', 'Lot ID','Wafer ID','Test Stage','Output Data Source','Test Program','Input Virtual DataSet','Output Virtual DataSet','Die X','Die Y','Orig X','Orig Y','Inkless Bin','Wafer MAP BIN','Rule 类型','Rule 名称'])
    df_mapping = gen_wafermap_config_mapping(info_dic,sql_info)
    lst = []
    for result_id in result_ids:
        rule_key = df_run_detail[df_run_detail['id']
                                 == result_id]['rule_key'].iloc[0]
        rule_alias = df_run_detail[df_run_detail['id']
                                   == result_id]['rule_alias'].iloc[0]
        test_stage = df_run_detail[df_run_detail['id']
                                   == result_id]['test_stage'].iloc[0]
        df_data_cluster = gen_data_cluster(result_id, sql_info)
        # ic(df_data_cluster)
        data = json.loads(df_data_cluster.iloc[0]['DATA'])
        df_data = pd.DataFrame(data['data']['dieOutputDTOList'])
        # ic(df_data)
        df_data = df_data[df_data['algHitFlag'] == 1].reset_index(drop=True)
        df_data=df_data[df_data['hbinPf']=='P']
        if len(df_data) == 0:
            continue
        df_data['originalDie'] = df_data.apply(
            lambda row: (row['x'], row['y']), axis=1)
        df_data = pd.merge(df_data, df_mapping, on='originalDie', how='left')

        df_data['Wafer MAP BIN'] = 'HBIN' + \
            df_data['hbinNum'].astype(str)+'-'+df_data['hbinName']
        # ic(df_data)

        df_axis = pd.DataFrame(index=range(len(df_data['x'])))
        df_axis['Lot ID'] = info_dic['Lot ID']
        df_axis['Wafer ID'] = wafer_id
        df_axis['Test Stage'] = test_stage
        input_virtual_id=df_run_detail[df_run_detail['id'] == result_id]['input_virtual_ids'].iloc[0]
        input_dict = info_dic['input_dict_for_mapping']
        output_dict = info_dic['output_dict_for_mapping']
        if ',' in input_virtual_id:
            df_axis['Output Data Source'] = mapping_char[output_dict[int(
                input_virtual_id.split(',')[0])]]
            res = ''
            for i in input_virtual_id.split(','):
                res += input_dict[int(i)]+','
            res = res[:-1]
            df_axis['Input Virtual DataSet'] = res
            df_axis['Output Virtual DataSet'] = input_dict[int(
                input_virtual_id.split(',')[0])]
        else:
            df_axis['Output Data Source'] = mapping_char[output_dict[int(input_virtual_id)]]
            df_axis['Test Program'] = ''
            df_axis['Input Virtual DataSet'] = input_dict[int(input_virtual_id)]
            df_axis['Output Virtual DataSet'] = input_dict[int(input_virtual_id)]
        df_axis['Test Program'] = ''

        df_axis['Die X'] = df_data['dieX']
        df_axis['Die Y'] = df_data['dieY']
        df_axis['Orig X'] = df_data['x']
        df_axis['Orig Y'] = df_data['y']
        df_axis['Inkless Bin'] = 'R'
        df_axis['Wafer MAP BIN'] = df_data['Wafer MAP BIN']
        df_axis['Rule 类型'] = rule_key
        df_axis['Rule 名称'] = rule_alias
        # ic(df_axis)

        lst.append(df_axis)
    df = pd.concat(lst, ignore_index=True)
    return df

def gen_RsDieSummary(df_run_detail, info_dic, sql_info):
    lst_RsDieSummary = []
    lot_wafer_id = info_dic['lot_wafer_id']
    for lot_id in lot_wafer_id.keys():
        for wafer_id in lot_wafer_id[lot_id]:
            RsDieSummary_one = gen_RsDieSummary_one(info_dic, df_run_detail, wafer_id, sql_info)
            if len(RsDieSummary_one)==0:
                continue
            lst_RsDieSummary.append(RsDieSummary_one)
    if len(lst_RsDieSummary)==0:
        RsDieSummary_df=pd.DataFrame(columns=['Lot ID', 'Lot ID', 'Wafer ID', 'Test Stage', 'Output Data Source', 'Test Program',
                              'Input Virtual DataSet', 'Output Virtual DataSet', 'Die X', 'Die Y', 'Orig X', 'Orig Y',
                              'Inkless Bin', 'Wafer MAP BIN', 'Rule 类型', 'Rule 名称'])
        info_dic['df_info']['RsDieSummary'] = {
            'col_num': len(RsDieSummary_df.columns),
            'row_num': len(RsDieSummary_df) + 1
        }
        return RsDieSummary_df

    RsDieSummary_df = pd.concat(lst_RsDieSummary, ignore_index=True)
    RsDieSummary_df.insert(0, 'No', range(1, len(RsDieSummary_df) + 1))
    info_dic['df_info']['RsDieSummary']={
        'col_num':len(RsDieSummary_df.columns),
        'row_num':len(RsDieSummary_df)+1
    }
    return RsDieSummary_df

if __name__ == '__main__':
    # from icecream import ic

    with open('./cfgs/input.json', 'r') as file:
        config = json.load(file)

    rule_run_record_id = config['recordId']
    sql_info = {}
    sql_info['mysqlInfo'] = config['mysqlInfo']
    sql_info['ckInfo'] = config['ckInfo']
    sql_info['dasHost'] = config['dasHost']
    re_file_path = config['fileFullPath']

    df_run_detail = gen_run_detail(rule_run_record_id, sql_info)
    info_dic=gen_info_dic(df_run_detail, sql_info)

    ##
    # wafer_id='NT41A_11'
    # df=gen_RsDieSummary_one(info_dic, df_run_detail, wafer_id, sql_info)
    # ic(df)
    # df.to_csv('cc.csv')
    ##
    df=gen_RsDieSummary(df_run_detail, info_dic, sql_info)
    # df.to_csv('dd.csv')

